import "./reset.css";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "./types";
import { getKeyList } from "@pureadmin/utils";
import { h, onMounted, reactive, ref, type Ref, toRaw } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { ElMessageBox } from "element-plus";
import { handleTree } from "@/utils/tree";
import { useUserStoreHook } from "@/store/modules/user";
export function useDealer(tableRef: Ref) {
  const form = reactive({
    Name: "", //经销商名称
    Code: "", //经销商编码
    Status: -1 //状态
  });
  const formRef = ref();
  const dataList = ref([]);
  const treeData = ref([]); // 添加树形数据引用
  const loading = ref(true);
  const switchLoadMap = ref({});
  const isInitializing = ref(true); // 添加初始化标志
  const { switchStyle } = usePublicHooks();
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    /* {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    }, */
    {
      label: "名称",
      prop: "Name",
      minWidth: 130,
      slot: "treeName",
      align: "left"
    },
    {
      label: "编码",
      prop: "Code",
      minWidth: 90
    },
    {
      label: "级别",
      prop: "Level",
      minWidth: 90
    },
    {
      label: "租户数量",
      prop: "TenantCount",
      minWidth: 90
    },
    {
      label: "状态",
      prop: "IsSealed",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.IsSealed}
          active-value={1}
          inactive-value={0}
          active-text="封闭"
          inactive-text="未封闭"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "联系人",
      prop: "Contact",
      minWidth: 90
    },
    {
      label: "电话",
      prop: "Tel",
      minWidth: 90
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  //获取、搜索经销商列表
  function onSearch() {
    const searchLimit = toRaw(form);
    const paginationInfo = toRaw(pagination);
    loading.value = true;
    const params: any = {
      PageIndex: paginationInfo.currentPage,
      pageSize: paginationInfo.pageSize,
      Name: searchLimit.Name,
      Code: searchLimit.Code,
      Status: searchLimit.Status
    };

    http
      .get(changeHttpLink("/api/Dealer"), { params })
      .then((res: any) => {
        loading.value = false;
        console.log("经销商数据", res);
        if (res.Success) {
          const newData = res.Data.Items;
          dataList.value = newData;
          pagination.total = res.Data.TotalCount;

          // 转换为树形结构
          treeData.value = handleTree(
            dataList.value,
            "Id",
            "ParentId",
            "children"
          );

          setTimeout(() => {
            loading.value = false;
            // 数据加载完成后，设置初始化完成
            isInitializing.value = false;
          }, 300);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //经销商新增、修改
  function openDialog(title, row: any) {
    const id = row?.Id ?? 0;
    addDialog({
      title: `${title}下级子经销商`,
      props: {
        formInline: {
          name: row?.Name ?? "",
          subLimit: row?.SubLimit ?? 20,
          tenantLimit: row?.TenantLimit ?? 20,
          isSealed: row?.IsSealed ?? 0,
          logo: row?.Logo ?? "",
          address: row?.Address ?? "",
          contact: row?.Contact ?? "",
          tel: row?.Tel ?? "",
          comment: row?.Comment ?? "",
          loginPwd: row?.LoginPwd ?? "", // 新增初始登录密码字段
          code: row?.Code ?? ""
        },
        title: title, // 传递title属性给表单组件
        originalName: row?.Name ?? ""
      },
      width: "680px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          ref: formRef,
          formInline: null,
          title,
          originalName: row.Name
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了经销商名称为【${curData.name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              Name: curData.name,
              SubLimit: curData.subLimit ?? 0,
              TenantLimit: curData.tenantLimit ?? 0,
              IsSealed: curData.isSealed,
              Logo: curData.logo,
              Address: curData.address,
              Contact: curData.contact,
              Tel: curData.tel,
              Comment: curData.comment,
              LoginPwd: curData.loginPwd, // 新增初始登录密码字段
              Code: curData.code
            };
            if (title == "创建") {
              console.log(title, formData);
              http
                .post(changeHttpLink("/api/Dealer"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                    onSearch();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else if (title !== "创建") {
              const updateData = {
                Id: id,
                Name: curData.name,
                Code: row.Code,
                Level: row.Level,
                SubSeed: row.SubSeed,
                SubLimit: curData.subLimit ?? 0,
                TenantLimit: curData.tenantLimit ?? 0,
                IsSealed: curData.isSealed,
                Logo: curData.logo,
                Address: curData.address,
                Contact: curData.contact,
                Tel: curData.tel,
                Comment: curData.comment
              };
              console.log(title, updateData);
              http
                .request("put", changeHttpLink(`/api/Dealer/${id}`), {
                  data: updateData
                })
                .then((res: any) => {
                  console.log("res", res);
                  if (res.Success) {
                    chores();
                    onSearch();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  message(err.message, { type: "error" });
                  loading.value = false;
                });
            }
          }
        });
      }
    });
  }
  /** 批量删除 */
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const params = {
      ids: curSelected.map(item => {
        return item.Id;
      })
    };
    /* const ids = curSelected.map(item => {
      return item.Id;
    }); */
    console.log(params);
    http
      .request("post", changeHttpLink("/api/Dealer/batch-delete"), {
        data: params
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(
            `您删除了ID为【 ${getKeyList(curSelected, "Id")}】的${curSelected.length}条数据`,
            {
              type: "success"
            }
          );
          tableRef.value.getTableRef().clearSelection();
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }
  //切换经销商状态
  function onChange({ row, index }) {
    // 如果正在初始化，则不执行onChange逻辑
    if (isInitializing.value) {
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>${
        row.IsSealed === 0 ? "启用" : "停用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.Name
      }</strong>经销商吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        http
          .post(changeHttpLink(`/api/Dealer/${row.Id}/toggle-status`), {
            data: {
              id: row.Id
            }
          })
          .then((res: any) => {
            if (res.Success) {
              message(`已${row.IsSealed === 0 ? "启用" : "停用"}${row.Name}`, {
                type: "success"
              });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
            loading.value = false;
          })
          .catch(err => {
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {});
  }
  //经销商数据删除
  function handleDelete(row) {
    http
      .request("delete", changeHttpLink(`/api/Dealer/${row.Id}`), {
        data: row.Id
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(`您删除了经销商名称为${row.Name}的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }
  //分页变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }
  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }
  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  // 设备检测
  function deviceDetection() {
    return window.innerWidth < 1200;
  }
  //获取经销商统计信息
  const statisticsData = ref({
    subCount: 0,
    subLimit: 0,
    tenantCount: 0,
    tenantLimit: 0,
    monthCardTotal: 0,
    monthCardAvailable: 0
  });
  function getStatisticsData() {
    const dealerId = useUserStoreHook()?.userId;
    http
      .get(changeHttpLink(`/api/Dealer/${dealerId}/statistics`), {
        params: dealerId
      })
      .then((res: any) => {
        if (res.Success) {
          const statistics = res.Data;
          console.log(statistics);
          // 更新统计数据
          statisticsData.value = {
            subCount: statistics.SubDealerCount || 0,
            subLimit: statistics.SubLimit || "不限",
            tenantCount: statistics.TenantCount || 0,
            tenantLimit: statistics.TenantLimit || "不限",
            monthCardTotal: 0, // 暂时显示0
            monthCardAvailable: 0 // 暂时显示0
          };
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }

  onMounted(() => {
    // 确保每次挂载时都重置初始化状态
    isInitializing.value = true;
    onSearch();
    getStatisticsData();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    treeData, // 返回树形数据
    deviceDetection,
    selectedNum,
    pagination,
    statisticsData,
    getStatisticsData,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
